package com.goldenautumn.prefabricate.utils

import android.R.attr
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.goldenautumn.prefabricate.R
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import qncx.external.common.constants.Intents.PERMISSIONS
import qncx.external.common.widget.dialog.PermissionDialog
import qncx.external.common.widget.view.TipsDialog
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File


object ImageSelectUtils {

    fun albumCamera(activity:FragmentActivity,isCamera:Boolean? = false, action: (path: String) -> Unit) {
        var permissions = PERMISSIONS
        if (!XXPermissions.isGranted(activity, permissions)) {
            PermissionDialog(activity.resources.getStringArray(R.array.user_agreement),3) {
                if(!it) TipsDialog.Builder(activity)
                    .setIcon(qncx.external.common.R.drawable.tips_warning_ic)
                    .setMessage("若拒绝相关权限\n将无法启动功能")
                    .show()
            }.onShow(activity.supportFragmentManager.beginTransaction())
            return
        }

        PictureSelector.create(activity)
            .openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(1)
            .isDisplayCamera(isCamera == true)
            .setImageEngine(GlideEngine1.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setCropEngine { fragment, srcUri, destinationUri, dataSource, requestCode ->
                var uCrop = UCrop.of(srcUri, destinationUri, dataSource)
                uCrop.setImageEngine(object : UCropImageEngine {

                    override fun loadImage(context: Context, url: String?, imageView: ImageView) {
                        context?.let { Glide.with(it).load(url).into(imageView) }
                    }

                    override fun loadImage(context: Context, url: Uri?, maxWidth: Int, maxHeight: Int, call: UCropImageEngine.OnCallbackListener<Bitmap>?) {
                        Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight).into(object : CustomTarget<Bitmap>() {
                            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                                call?.onCall(resource)
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {
                                call?.onCall(null)
                            }
                        })
                    }
                })
                uCrop.withOptions(buildOptions())
                uCrop.start(activity, fragment, requestCode)
            }.forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let {
                        if (it.size > 0) {
                            var image = it[0]
                            var path = if (!image.cutPath.isNullOrEmpty()) image.cutPath else image.path
                            action(path)
                        }
                    }
                }

                override fun onCancel() {

                }
            })

    }

    fun animeAlbumCamera(activity:FragmentActivity,action: (path: String) -> Unit) {
        var permissions = PERMISSIONS
        if (!XXPermissions.isGranted(activity, permissions)) {
            PermissionDialog(activity.resources.getStringArray(R.array.user_agreement),3) {
                if(!it) TipsDialog.Builder(activity)
                    .setIcon(qncx.external.common.R.drawable.tips_warning_ic)
                    .setMessage("若拒绝相关权限\n将无法启动功能")
                    .show()
            }.onShow(activity.supportFragmentManager.beginTransaction())
            return
        }

        PictureSelector.create(activity)
            .openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(1)
            .isDisplayCamera(false)
            .setImageEngine(GlideEngine1.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let {
                        if (it.size > 0) action(if(it[0].realPath.isNullOrEmpty()) it[0].path else it[0].realPath)
                    }
                }

                override fun onCancel() {

                }
            })

    }

    fun dynamicAlbumCamera(activity:FragmentActivity,oldData:ArrayList<LocalMedia>? = null,action: (path: ArrayList<LocalMedia>) -> Unit) {
        var permissions = PERMISSIONS
        if (!XXPermissions.isGranted(activity, permissions)) {
            PermissionDialog(activity.resources.getStringArray(R.array.user_agreement),3) {
                if(!it) TipsDialog.Builder(activity)
                    .setIcon(qncx.external.common.R.drawable.tips_warning_ic)
                    .setMessage("若拒绝相关权限\n将无法启动功能")
                    .show()
            }.onShow(activity.supportFragmentManager.beginTransaction())
            return
        }

        PictureSelector.create(activity)
            .openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(9)
            .setSelectedData(oldData)
            .isDisplayCamera(true)
            .setImageEngine(GlideEngine1.createGlideEngine())
            .setCompressEngine(CompressFileEngine { context, source, call ->
                Luban.with(context).load(source).ignoreBy(200)
                    .setCompressListener(object : OnNewCompressListener {
                        override fun onStart() {

                        }

                        override fun onSuccess(source: String?, compressFile: File?) {
                            call?.onCallback(source, compressFile?.absolutePath)
                        }

                        override fun onError(source: String?, e: Throwable?) {
                            call?.onCallback(source, null)
                        }
                    }).launch()
            }).forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.let { action(result) }
                }

                override fun onCancel() {

                }
            })

    }

    class ImageFileCompressEngine :CompressFileEngine{
        override fun onStartCompress(context: Context?, source: java.util.ArrayList<Uri>?, call: OnKeyValueResultCallbackListener?) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener { filePath ->
                val indexOf: Int = filePath.lastIndexOf(".")
                val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                DateUtils.getCreateFileName("CMP_") + postfix
            }.filter { path ->
                if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) true
                !PictureMimeType.isUrlHasGif(path)
            }.setCompressListener(object :OnNewCompressListener{
                override fun onStart() {

                }

                override fun onSuccess(source: String?, compressFile: File?) {
                    call?.onCallback(source, compressFile?.absolutePath)
                }

                override fun onError(source: String?, e: Throwable?) {
                    call?.onCallback(source, null)
                }
            }).launch()
        }
    }

    private fun buildOptions(): UCrop.Options {
        val options = UCrop.Options()
        options.withAspectRatio(1f, 1f)
        options.withMaxResultSize(500,500)
        return options
    }

}